//
// Created by Administrator on 2017/3/15 0015.
//
#include <stdio.h>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfiltergraph.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/avutil.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"

static FILE *fp_open;

static int fill_iobuffer(void *opaque, uint8_t *buf, int buf_size)
{
    if (!feof(fp_open))
    {
        return fread(buf, 1, buf_size, fp_open);
    }
    else
    {
        return -1;
    }
}

static int open_input_file()
{
    fp_open = fopen("D:/to.h264", "rb+");
    av_register_all();
    int ret;
    unsigned int i;
    AVFormatContext *ifmt_ctx = avformat_alloc_context();
    unsigned char *iobuffer = av_malloc(32768);
    AVIOContext *avio = avio_alloc_context(iobuffer, 32768, 0, NULL, &fill_iobuffer, NULL, NULL);
    ifmt_ctx->pb = avio;

    if ((ret = avformat_open_input(&ifmt_ctx, NULL, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        char *buf = malloc(1024);
        memset(buf, 0, 1024);
        av_strerror(ret, buf, 1024);
        printf("%d(%s)", ret, buf);
        return ret;
    }
    if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
        return ret;
    }
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        AVStream *stream;
        AVCodecParameters *codec_params;
        AVCodecContext *avctx;
        AVCodec *input_codec;

        stream = ifmt_ctx->streams[i];
        codec_params = stream->codecpar;

        input_codec = avcodec_find_decoder(codec_params->codec_id);
        avctx = avcodec_alloc_context3(input_codec);

        /* Reencode video & audio and remux subtitles etc. */
        if (codec_params->codec_type == AVMEDIA_TYPE_VIDEO
            || codec_params->codec_type == AVMEDIA_TYPE_AUDIO) {
            /* Open decoder */

            avcodec_parameters_to_context(avctx, codec_params);
            ret = avcodec_open2(avctx, input_codec, NULL);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
                return ret;
            }
        }
    }
    av_dump_format(ifmt_ctx, 0, "nothing", 0);
    return 0;
}
